<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,springboot,mybatis,druid,pagehelper," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言本篇文章主要讲述的是SpringBoot整合Mybatis、Druid和PageHelper 并实现多数据源和分页。其中SpringBoot整合Mybatis这块，在之前的的一篇文章中已经讲述了，这里就不过多说明了。重点是讲述在多数据源下的如何配置使用Druid和PageHelper 。 Druid介绍和使用在使用Druid之前，先来简单的了解下Druid。 Druid是一个数据库连接池。D">
<meta name="keywords" content="java,springboot,mybatis,druid,pagehelper">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页">
<meta property="og:url" content="http://yoursite.com/2018/04/27/pancm81/index.html">
<meta property="og:site_name" content="虚无境的博客">
<meta property="og:description" content="前言本篇文章主要讲述的是SpringBoot整合Mybatis、Druid和PageHelper 并实现多数据源和分页。其中SpringBoot整合Mybatis这块，在之前的的一篇文章中已经讲述了，这里就不过多说明了。重点是讲述在多数据源下的如何配置使用Druid和PageHelper 。 Druid介绍和使用在使用Druid之前，先来简单的了解下Druid。 Druid是一个数据库连接池。D">
<meta property="og:image" content="https://img-blog.csdn.net/20180427222208271?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FhendzeHBjbQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:updated_time" content="2018-04-28T13:31:54.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页">
<meta name="twitter:description" content="前言本篇文章主要讲述的是SpringBoot整合Mybatis、Druid和PageHelper 并实现多数据源和分页。其中SpringBoot整合Mybatis这块，在之前的的一篇文章中已经讲述了，这里就不过多说明了。重点是讲述在多数据源下的如何配置使用Druid和PageHelper 。 Druid介绍和使用在使用Druid之前，先来简单的了解下Druid。 Druid是一个数据库连接池。D">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180427222208271?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FhendzeHBjbQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/04/27/pancm81/"/>






  <title>SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页 | 虚无境的博客</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?39c177d10f6e05ddfa113e02139b9c1c";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">虚无境的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/04/27/pancm81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="虚无境">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/xuwujing.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="虚无境的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-27T22:34:18+08:00">
                2018-04-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>本篇文章主要讲述的是<strong>SpringBoot</strong>整合<strong>Mybatis</strong>、<strong>Druid</strong>和<strong>PageHelper</strong> 并实现多数据源和分页。其中SpringBoot整合Mybatis这块，在之前的的<a href="http://www.cnblogs.com/xuwujing/p/8260935.html" target="_blank" rel="external">一篇文章</a>中已经讲述了，这里就不过多说明了。重点是讲述在多数据源下的如何配置使用Druid和PageHelper 。</p>
<h2 id="Druid介绍和使用"><a href="#Druid介绍和使用" class="headerlink" title="Druid介绍和使用"></a>Druid介绍和使用</h2><p>在使用<strong>Druid</strong>之前，先来简单的了解下Druid。</p>
<p>Druid是一个数据库连接池。Druid可以说是目前最好的数据库连接池！因其优秀的功能、性能和扩展性方面，深受开发人员的青睐。<br>Druid已经在阿里巴巴部署了超过600个应用，经过一年多生产环境大规模部署的严苛考验。Druid是阿里巴巴开发的号称为监控而生的数据库连接池！</p>
<p>同时Druid不仅仅是一个数据库连接池，Druid 核心主要包括三部分：</p>
<ul>
<li>基于Filter－Chain模式的插件体系。</li>
<li>DruidDataSource 高效可管理的数据库连接池。</li>
<li>SQLParser</li>
</ul>
<p>Druid的主要功能如下:</p>
<ol>
<li>是一个高效、功能强大、可扩展性好的数据库连接池。</li>
<li>可以监控数据库访问性能。</li>
<li>数据库密码加密</li>
<li>获得SQL执行日志</li>
<li>扩展JDBC</li>
</ol>
<p>介绍方面这块就不再多说，具体的可以看官方文档。<br>那么开始介绍Druid如何使用。</p>
<p>首先是Maven依赖，只需要添加druid这一个jar就行了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&lt;dependency&gt;</div><div class="line">         &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</div><div class="line">         &lt;artifactId&gt;druid&lt;/artifactId&gt;</div><div class="line">         &lt;version&gt;1.1.8&lt;/version&gt;</div><div class="line">  &lt;/dependency&gt;</div></pre></td></tr></table></figure>
<p>配置方面，主要的只需要在<strong>application.properties</strong>或<strong>application.yml</strong>添加如下就可以了。<br><strong>说明：因为这里我是用来两个数据源，所以稍微有些不同而已。Druid 配置的说明在下面中已经说的很详细了，这里我就不在说明了。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line">## 默认的数据源</div><div class="line"></div><div class="line">master.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&amp;characterEncoding=utf8&amp;allowMultiQueries=true</div><div class="line">master.datasource.username=root</div><div class="line">master.datasource.password=123456</div><div class="line">master.datasource.driverClassName=com.mysql.jdbc.Driver</div><div class="line"></div><div class="line"></div><div class="line">## 另一个的数据源</div><div class="line">cluster.datasource.url=jdbc:mysql://localhost:3306/springBoot_test?useUnicode=true&amp;characterEncoding=utf8</div><div class="line">cluster.datasource.username=root</div><div class="line">cluster.datasource.password=123456</div><div class="line">cluster.datasource.driverClassName=com.mysql.jdbc.Driver</div><div class="line"></div><div class="line"># 连接池的配置信息  </div><div class="line"># 初始化大小，最小，最大  </div><div class="line">spring.datasource.type=com.alibaba.druid.pool.DruidDataSource</div><div class="line">spring.datasource.initialSize=5  </div><div class="line">spring.datasource.minIdle=5  </div><div class="line">spring.datasource.maxActive=20  </div><div class="line"># 配置获取连接等待超时的时间  </div><div class="line">spring.datasource.maxWait=60000  </div><div class="line"># 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒  </div><div class="line">spring.datasource.timeBetweenEvictionRunsMillis=60000  </div><div class="line"># 配置一个连接在池中最小生存的时间，单位是毫秒  </div><div class="line">spring.datasource.minEvictableIdleTimeMillis=300000  </div><div class="line">spring.datasource.validationQuery=SELECT 1 FROM DUAL  </div><div class="line">spring.datasource.testWhileIdle=true  </div><div class="line">spring.datasource.testOnBorrow=false  </div><div class="line">spring.datasource.testOnReturn=false  </div><div class="line"># 打开PSCache，并且指定每个连接上PSCache的大小  </div><div class="line">spring.datasource.poolPreparedStatements=true  </div><div class="line">spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  </div><div class="line"># 配置监控统计拦截的filters，去掉后监控界面sql无法统计，&apos;wall&apos;用于防火墙  </div><div class="line">spring.datasource.filters=stat,wall,log4j  </div><div class="line"># 通过connectProperties属性来打开mergeSql功能；慢SQL记录  </div><div class="line">spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000</div></pre></td></tr></table></figure>
<p> 成功添加了配置文件之后，我们再来编写Druid相关的类。<br> 首先是<strong>MasterDataSourceConfig.java</strong>这个类，这个是默认的数据源配置类。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div></pre></td><td class="code"><pre><div class="line">@Configuration</div><div class="line">@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = &quot;masterSqlSessionFactory&quot;)</div><div class="line">public class MasterDataSourceConfig &#123;</div><div class="line"></div><div class="line">    static final String PACKAGE = &quot;com.pancm.dao.master&quot;;</div><div class="line">    static final String MAPPER_LOCATION = &quot;classpath:mapper/master/*.xml&quot;;</div><div class="line"></div><div class="line">    @Value(&quot;$&#123;master.datasource.url&#125;&quot;)  </div><div class="line">    private String url;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;master.datasource.username&#125;&quot;)  </div><div class="line">    private String username;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;master.datasource.password&#125;&quot;)  </div><div class="line">    private String password;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;master.datasource.driverClassName&#125;&quot;)  </div><div class="line">    private String driverClassName;  </div><div class="line">      </div><div class="line">    </div><div class="line">    </div><div class="line">    </div><div class="line">    @Value(&quot;$&#123;spring.datasource.initialSize&#125;&quot;)  </div><div class="line">    private int initialSize;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.minIdle&#125;&quot;)  </div><div class="line">    private int minIdle;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.maxActive&#125;&quot;)  </div><div class="line">    private int maxActive;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.maxWait&#125;&quot;)  </div><div class="line">    private int maxWait;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.timeBetweenEvictionRunsMillis&#125;&quot;)  </div><div class="line">    private int timeBetweenEvictionRunsMillis;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.minEvictableIdleTimeMillis&#125;&quot;)  </div><div class="line">    private int minEvictableIdleTimeMillis;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.validationQuery&#125;&quot;)  </div><div class="line">    private String validationQuery;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.testWhileIdle&#125;&quot;)  </div><div class="line">    private boolean testWhileIdle;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.testOnBorrow&#125;&quot;)  </div><div class="line">    private boolean testOnBorrow;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.testOnReturn&#125;&quot;)  </div><div class="line">    private boolean testOnReturn;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.poolPreparedStatements&#125;&quot;)  </div><div class="line">    private boolean poolPreparedStatements;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.maxPoolPreparedStatementPerConnectionSize&#125;&quot;)  </div><div class="line">    private int maxPoolPreparedStatementPerConnectionSize;  </div><div class="line">      </div><div class="line">    @Value(&quot;$&#123;spring.datasource.filters&#125;&quot;)  </div><div class="line">    private String filters;  </div><div class="line">      </div><div class="line">    @Value(&quot;&#123;spring.datasource.connectionProperties&#125;&quot;)  </div><div class="line">    private String connectionProperties;  </div><div class="line">    </div><div class="line">    </div><div class="line">    @Bean(name = &quot;masterDataSource&quot;)</div><div class="line">    @Primary </div><div class="line">    public DataSource masterDataSource() &#123;</div><div class="line">        DruidDataSource dataSource = new DruidDataSource();</div><div class="line">        dataSource.setUrl(url);  </div><div class="line">        dataSource.setUsername(username);  </div><div class="line">        dataSource.setPassword(password);  </div><div class="line">        dataSource.setDriverClassName(driverClassName);  </div><div class="line">          </div><div class="line">        //具体配置 </div><div class="line">        dataSource.setInitialSize(initialSize);  </div><div class="line">        dataSource.setMinIdle(minIdle);  </div><div class="line">        dataSource.setMaxActive(maxActive);  </div><div class="line">        dataSource.setMaxWait(maxWait);  </div><div class="line">        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  </div><div class="line">        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  </div><div class="line">        dataSource.setValidationQuery(validationQuery);  </div><div class="line">        dataSource.setTestWhileIdle(testWhileIdle);  </div><div class="line">        dataSource.setTestOnBorrow(testOnBorrow);  </div><div class="line">        dataSource.setTestOnReturn(testOnReturn);  </div><div class="line">        dataSource.setPoolPreparedStatements(poolPreparedStatements);  </div><div class="line">        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);  </div><div class="line">        try &#123;  </div><div class="line">            dataSource.setFilters(filters);  </div><div class="line">        &#125; catch (SQLException e) &#123; </div><div class="line">        	e.printStackTrace();</div><div class="line">        &#125;  </div><div class="line">        dataSource.setConnectionProperties(connectionProperties);  </div><div class="line">        return dataSource;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Bean(name = &quot;masterTransactionManager&quot;)</div><div class="line">    @Primary</div><div class="line">    public DataSourceTransactionManager masterTransactionManager() &#123;</div><div class="line">        return new DataSourceTransactionManager(masterDataSource());</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Bean(name = &quot;masterSqlSessionFactory&quot;)</div><div class="line">    @Primary</div><div class="line">    public SqlSessionFactory masterSqlSessionFactory(@Qualifier(&quot;masterDataSource&quot;) DataSource masterDataSource)</div><div class="line">            throws Exception &#123;</div><div class="line">        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();</div><div class="line">        sessionFactory.setDataSource(masterDataSource);</div><div class="line">        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()</div><div class="line">                .getResources(MasterDataSourceConfig.MAPPER_LOCATION));</div><div class="line">        return sessionFactory.getObject();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其中这两个注解说明下:</p>
<ul>
<li><p><strong>@Primary</strong> ：标志这个 Bean 如果在多个同类 Bean 候选时，该 Bean<br>优先被考虑。多数据源配置的时候注意，必须要有一个主数据源，用 @Primary 标志该 Bean。</p>
</li>
<li><p><strong>@MapperScan</strong>： 扫描 Mapper 接口并容器管理。</p>
</li>
</ul>
<p>需要注意的是<strong>sqlSessionFactoryRef</strong> 表示定义一个唯一 <strong>SqlSessionFactory</strong> 实例。</p>
<p>上面的配置完之后，就可以将Druid作为连接池使用了。但是Druid并不简简单单的是个连接池，它也可以说是一个监控应用，它自带了web监控界面，可以很清晰的看到SQL相关信息。<br>在<strong>SpringBoot</strong>中运用<strong>Druid</strong>的监控作用，只需要编写<strong>StatViewServlet</strong>和<strong>WebStatFilter</strong>类，实现注册服务和过滤规则。这里我们可以将这两个写在一起，使用<strong>@Configuration</strong>和<strong>@Bean</strong>。<br>为了方便理解，相关的配置说明也写在代码中了，这里就不再过多赘述了。<br>代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line">@Configuration</div><div class="line">public class DruidConfiguration &#123;</div><div class="line"></div><div class="line">	@Bean</div><div class="line">	public ServletRegistrationBean druidStatViewServle() &#123;</div><div class="line">		//注册服务</div><div class="line">		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(</div><div class="line">				new StatViewServlet(), &quot;/druid/*&quot;);</div><div class="line">		// 白名单(为空表示,所有的都可以访问,多个IP的时候用逗号隔开)</div><div class="line">		servletRegistrationBean.addInitParameter(&quot;allow&quot;, &quot;127.0.0.1&quot;);</div><div class="line">		// IP黑名单 (存在共同时，deny优先于allow) </div><div class="line">		servletRegistrationBean.addInitParameter(&quot;deny&quot;, &quot;127.0.0.2&quot;);</div><div class="line">		// 设置登录的用户名和密码</div><div class="line">		servletRegistrationBean.addInitParameter(&quot;loginUsername&quot;, &quot;pancm&quot;);</div><div class="line">		servletRegistrationBean.addInitParameter(&quot;loginPassword&quot;, &quot;123456&quot;);</div><div class="line">		// 是否能够重置数据.</div><div class="line">		servletRegistrationBean.addInitParameter(&quot;resetEnable&quot;, &quot;false&quot;);</div><div class="line">		return servletRegistrationBean;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	@Bean</div><div class="line">	public FilterRegistrationBean druidStatFilter() &#123;</div><div class="line">		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(</div><div class="line">				new WebStatFilter());</div><div class="line">		// 添加过滤规则</div><div class="line">		filterRegistrationBean.addUrlPatterns(&quot;/*&quot;);</div><div class="line">		// 添加不需要忽略的格式信息</div><div class="line">		filterRegistrationBean.addInitParameter(&quot;exclusions&quot;,</div><div class="line">				&quot;*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*&quot;);</div><div class="line">		System.out.println(&quot;druid初始化成功!&quot;);</div><div class="line">		return filterRegistrationBean;</div><div class="line"></div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>编写完之后，启动程序，在浏览器输入:<a href="http://127.0.0.1:8084/druid/index.html" target="_blank" rel="external">http://127.0.0.1:8084/druid/index.html</a> ，然后输入设置的用户名和密码，便可以访问Web界面了。</p>
<h2 id="多数据源配置"><a href="#多数据源配置" class="headerlink" title="多数据源配置"></a>多数据源配置</h2><p>在进行多数据源配置之前，先分别在<strong>springBoot</strong>和<strong>springBoot_test</strong>的<strong>mysql</strong>数据库中执行如下脚本。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">-- springBoot库的脚本</div><div class="line"></div><div class="line">CREATE TABLE `t_user` (</div><div class="line">  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT &apos;自增id&apos;,</div><div class="line">  `name` varchar(10) DEFAULT NULL COMMENT &apos;姓名&apos;,</div><div class="line">  `age` int(2) DEFAULT NULL COMMENT &apos;年龄&apos;,</div><div class="line">  PRIMARY KEY (`id`)</div><div class="line">) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8</div><div class="line"></div><div class="line">-- springBoot_test库的脚本</div><div class="line"></div><div class="line">CREATE TABLE `t_student` (</div><div class="line">  `id` int(11) NOT NULL AUTO_INCREMENT,</div><div class="line">  `name` varchar(16) DEFAULT NULL,</div><div class="line">  `age` int(11) DEFAULT NULL,</div><div class="line">  PRIMARY KEY (`id`)</div><div class="line">) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8</div></pre></td></tr></table></figure>
<p><strong>注:为了偷懒，将两张表的结构弄成一样了！不过不影响测试!</strong></p>
<p>在<strong>application.properties</strong>中已经配置这两个数据源的信息，上面已经贴出了一次配置，这里就不再贴了。<br>这里重点说下 第二个数据源的配置。和上面的<strong>MasterDataSourceConfig.java</strong>差不多，区别在与没有使用<strong>@Primary</strong> 注解和名称不同而已。需要注意的是<strong>MasterDataSourceConfig.java</strong>对package和mapper的扫描是精确到目录的，这里的第二个数据源也是如此。那么代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div></pre></td><td class="code"><pre><div class="line">@Configuration</div><div class="line">@MapperScan(basePackages = ClusterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = &quot;clusterSqlSessionFactory&quot;)</div><div class="line">public class ClusterDataSourceConfig &#123;</div><div class="line"></div><div class="line"> static final String PACKAGE = &quot;com.pancm.dao.cluster&quot;;</div><div class="line"> static final String MAPPER_LOCATION = &quot;classpath:mapper/cluster/*.xml&quot;;</div><div class="line"></div><div class="line"> @Value(&quot;$&#123;cluster.datasource.url&#125;&quot;)</div><div class="line"> private String url;</div><div class="line"></div><div class="line"> @Value(&quot;$&#123;cluster.datasource.username&#125;&quot;)</div><div class="line"> private String username;</div><div class="line"></div><div class="line"> @Value(&quot;$&#123;cluster.datasource.password&#125;&quot;)</div><div class="line"> private String password;</div><div class="line"></div><div class="line"> @Value(&quot;$&#123;cluster.datasource.driverClassName&#125;&quot;)</div><div class="line"> private String driverClass;</div><div class="line"></div><div class="line"> // 和MasterDataSourceConfig一样，这里略</div><div class="line"></div><div class="line"> @Bean(name = &quot;clusterDataSource&quot;)</div><div class="line"> public DataSource clusterDataSource() &#123;</div><div class="line">     DruidDataSource dataSource = new DruidDataSource();</div><div class="line">     dataSource.setUrl(url);  </div><div class="line">     dataSource.setUsername(username);  </div><div class="line">     dataSource.setPassword(password);  </div><div class="line">     dataSource.setDriverClassName(driverClass);  </div><div class="line">   </div><div class="line">     // 和MasterDataSourceConfig一样，这里略 ...</div><div class="line">     return dataSource;</div><div class="line"> &#125;</div><div class="line"></div><div class="line"> @Bean(name = &quot;clusterTransactionManager&quot;)</div><div class="line"> public DataSourceTransactionManager clusterTransactionManager() &#123;</div><div class="line">     return new DataSourceTransactionManager(clusterDataSource());</div><div class="line"> &#125;</div><div class="line"></div><div class="line"> @Bean(name = &quot;clusterSqlSessionFactory&quot;)</div><div class="line"> public SqlSessionFactory clusterSqlSessionFactory(@Qualifier(&quot;clusterDataSource&quot;) DataSource clusterDataSource)</div><div class="line">         throws Exception &#123;</div><div class="line">     final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();</div><div class="line">     sessionFactory.setDataSource(clusterDataSource);</div><div class="line">     sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ClusterDataSourceConfig.MAPPER_LOCATION));</div><div class="line">     return sessionFactory.getObject();</div><div class="line"> &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>成功写完配置之后，启动程序，进行测试。<br>分别在<strong>springBoot</strong>和<strong>springBoot_test</strong>库中使用接口进行添加数据。</p>
<p><strong>t_user</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">POST http://localhost:8084/api/user</div><div class="line">&#123;&quot;name&quot;:&quot;张三&quot;,&quot;age&quot;:25&#125;</div><div class="line">&#123;&quot;name&quot;:&quot;李四&quot;,&quot;age&quot;:25&#125;</div><div class="line">&#123;&quot;name&quot;:&quot;王五&quot;,&quot;age&quot;:25&#125;</div></pre></td></tr></table></figure>
<p><strong>t_student</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">POST http://localhost:8084/api/student</div><div class="line">&#123;&quot;name&quot;:&quot;学生A&quot;,&quot;age&quot;:16&#125;</div><div class="line">&#123;&quot;name&quot;:&quot;学生B&quot;,&quot;age&quot;:17&#125;</div><div class="line">&#123;&quot;name&quot;:&quot;学生C&quot;,&quot;age&quot;:18&#125;</div></pre></td></tr></table></figure>
<p>成功添加数据之后，然后进行调用不同的接口进行查询。</p>
<p>请求:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">GET http://localhost:8084/api/user?name=李四</div></pre></td></tr></table></figure></p>
<p>返回:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    &quot;id&quot;: 2,</div><div class="line">    &quot;name&quot;: &quot;李四&quot;,</div><div class="line">    &quot;age&quot;: 25</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>请求:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">GET http://localhost:8084/api/student?name=学生C</div></pre></td></tr></table></figure></p>
<p>返回:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    &quot;id&quot;: 1,</div><div class="line">    &quot;name&quot;: &quot;学生C&quot;,</div><div class="line">    &quot;age&quot;: 16</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>通过数据可以看出，成功配置了多数据源了。</p>
<h2 id="PageHelper-分页实现"><a href="#PageHelper-分页实现" class="headerlink" title="PageHelper 分页实现"></a>PageHelper 分页实现</h2><p>PageHelper是Mybatis的一个分页插件，非常的好用！这里强烈推荐！！！</p>
<p>PageHelper的使用很简单，只需要在Maven中添加pagehelper这个依赖就可以了。<br>Maven的依赖如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"> &lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;pagehelper-spring-boot-starter&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;1.2.3&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div></pre></td></tr></table></figure>
<p><strong>注：这里我是用springBoot版的！也可以使用其它版本的。</strong></p>
<p>添加依赖之后，只需要添加如下配置或代码就可以了。<br>第一种，在<strong>application.properties</strong>或<strong>application.yml</strong>添加</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">pagehelper:</div><div class="line">helperDialect: mysql</div><div class="line">offsetAsPageNum: true</div><div class="line">rowBoundsWithCount: true</div><div class="line">reasonable: false</div></pre></td></tr></table></figure>
<p>第二种，在mybatis.xml配置中添加</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">&lt;bean id=&quot;sqlSessionFactory&quot; class=&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;&gt;</div><div class="line">  &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot; /&gt;</div><div class="line">  &lt;!-- 扫描mapping.xml文件 --&gt;</div><div class="line">  &lt;property name=&quot;mapperLocations&quot; value=&quot;classpath:mapper/*.xml&quot;&gt;&lt;/property&gt;</div><div class="line">  &lt;!-- 配置分页插件 --&gt;</div><div class="line">   &lt;property name=&quot;plugins&quot;&gt;</div><div class="line">      &lt;array&gt;</div><div class="line">        &lt;bean class=&quot;com.github.pagehelper.PageHelper&quot;&gt;</div><div class="line">          &lt;property name=&quot;properties&quot;&gt;</div><div class="line">            &lt;value&gt;</div><div class="line">              helperDialect=mysql</div><div class="line">		offsetAsPageNum=true</div><div class="line">		rowBoundsWithCount=true</div><div class="line">		reasonable=false</div><div class="line">            &lt;/value&gt;</div><div class="line">          &lt;/property&gt;</div><div class="line">        &lt;/bean&gt;</div><div class="line">      &lt;/array&gt;</div><div class="line">    &lt;/property&gt;</div><div class="line">&lt;/bean&gt;</div></pre></td></tr></table></figure>
<p>第三种，在代码中添加，使用<strong>@Bean</strong>注解在启动程序的时候初始化。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">@Bean</div><div class="line"> public PageHelper pageHelper()&#123;</div><div class="line">   PageHelper pageHelper = new PageHelper();</div><div class="line">  Properties properties = new Properties();</div><div class="line">  //数据库</div><div class="line">  properties.setProperty(&quot;helperDialect&quot;, &quot;mysql&quot;);</div><div class="line">  //是否将参数offset作为PageNum使用</div><div class="line">  properties.setProperty(&quot;offsetAsPageNum&quot;, &quot;true&quot;);</div><div class="line">  //是否进行count查询</div><div class="line">  properties.setProperty(&quot;rowBoundsWithCount&quot;, &quot;true&quot;);</div><div class="line">  //是否分页合理化</div><div class="line">  properties.setProperty(&quot;reasonable&quot;, &quot;false&quot;);</div><div class="line">  pageHelper.setProperties(properties);</div><div class="line"> &#125;</div></pre></td></tr></table></figure>
<p>因为这里我们使用的是多数据源，所以这里的配置稍微有些不同。我们需要在<strong>sessionFactory</strong>这里配置。这里就对<strong>MasterDataSourceConfig.java</strong>进行相应的修改。在<strong>masterSqlSessionFactory</strong>方法中，添加如下代码。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line">  @Bean(name = &quot;masterSqlSessionFactory&quot;)</div><div class="line">  @Primary</div><div class="line">  public SqlSessionFactory masterSqlSessionFactory(@Qualifier(&quot;masterDataSource&quot;) DataSource masterDataSource)</div><div class="line">          throws Exception &#123;</div><div class="line">      final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();</div><div class="line">      sessionFactory.setDataSource(masterDataSource);</div><div class="line">      sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()</div><div class="line">              .getResources(MasterDataSourceConfig.MAPPER_LOCATION));</div><div class="line">      //分页插件</div><div class="line">      Interceptor interceptor = new PageInterceptor();</div><div class="line">      Properties properties = new Properties();</div><div class="line">      //数据库</div><div class="line">      properties.setProperty(&quot;helperDialect&quot;, &quot;mysql&quot;);</div><div class="line">      //是否将参数offset作为PageNum使用</div><div class="line">      properties.setProperty(&quot;offsetAsPageNum&quot;, &quot;true&quot;);</div><div class="line">      //是否进行count查询</div><div class="line">      properties.setProperty(&quot;rowBoundsWithCount&quot;, &quot;true&quot;);</div><div class="line">      //是否分页合理化</div><div class="line">      properties.setProperty(&quot;reasonable&quot;, &quot;false&quot;);</div><div class="line">      interceptor.setProperties(properties);</div><div class="line">      sessionFactory.setPlugins(new Interceptor[] &#123;interceptor&#125;);</div><div class="line">      </div><div class="line">  return sessionFactory.getObject();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>注：其它的数据源也想进行分页的时候，参照上面的代码即可。</strong></p>
<p>这里需要注意的是<strong>reasonable</strong>参数，表示分页合理化，默认值为false。如果该参数设置为 true 时，pageNum&lt;=0 时会查询第一页，pageNum&gt;pages（超过总数时），会查询最后一页。默认false 时，直接根据参数进行查询。</p>
<p>设置完PageHelper 之后，使用的话，只需要在查询的sql前面添加<strong>PageHelper.startPage(pageNum,pageSize);</strong>，如果是想知道总数的话，在查询的sql语句后买呢添加 <strong>page.getTotal()</strong>就可以了。<br>代码示例:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">public List&lt;T&gt; findByListEntity(T entity) &#123;</div><div class="line">		List&lt;T&gt; list = null;</div><div class="line">		try &#123;</div><div class="line">			Page&lt;?&gt; page =PageHelper.startPage(1,2); </div><div class="line">			System.out.println(getClassName(entity)+&quot;设置第一页两条数据!&quot;);</div><div class="line">			list = getMapper().findByListEntity(entity);</div><div class="line">			System.out.println(&quot;总共有:&quot;+page.getTotal()+&quot;条数据,实际返回:&quot;+list.size()+&quot;两条数据!&quot;);</div><div class="line">		&#125; catch (Exception e) &#123;</div><div class="line">			logger.error(&quot;查询&quot;+getClassName(entity)+&quot;失败!原因是:&quot;,e);</div><div class="line">		&#125;</div><div class="line">		return list;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p>代码编写完毕之后，开始进行最后的测试。</p>
<p>查询<strong>t_user</strong>表的所有的数据，并进行分页。</p>
<p>请求:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">GET http://localhost:8084/api/user</div></pre></td></tr></table></figure></p>
<p>返回:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">[</div><div class="line">    &#123;</div><div class="line">        &quot;id&quot;: 1,</div><div class="line">        &quot;name&quot;: &quot;张三&quot;,</div><div class="line">        &quot;age&quot;: 25</div><div class="line">    &#125;,</div><div class="line">    &#123;</div><div class="line">        &quot;id&quot;: 2,</div><div class="line">        &quot;name&quot;: &quot;李四&quot;,</div><div class="line">        &quot;age&quot;: 25</div><div class="line">    &#125;</div><div class="line">]</div></pre></td></tr></table></figure>
<p>控制台打印:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">开始查询...</div><div class="line">User设置第一页两条数据!</div><div class="line">2018-04-27 19:55:50.769 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT   : ==&gt;  Preparing: SELECT count(0) FROM t_user WHERE 1 = 1 </div><div class="line">2018-04-27 19:55:50.770 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT   : ==&gt; Parameters: </div><div class="line">2018-04-27 19:55:50.771 DEBUG 6152 --- [io-8084-exec-10] c.p.d.m.UserDao.findByListEntity_COUNT   : &lt;==      Total: 1</div><div class="line">2018-04-27 19:55:50.772 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity  : ==&gt;  Preparing: select id, name, age from t_user where 1=1 LIMIT ? </div><div class="line">2018-04-27 19:55:50.773 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity  : ==&gt; Parameters: 2(Integer)</div><div class="line">2018-04-27 19:55:50.774 DEBUG 6152 --- [io-8084-exec-10] c.p.dao.master.UserDao.findByListEntity  : &lt;==      Total: 2</div><div class="line">总共有:3条数据,实际返回:2两条数据!</div></pre></td></tr></table></figure>
<p>查询<strong>t_student</strong>表的所有的数据，并进行分页。</p>
<p>请求:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">GET  http://localhost:8084/api/student</div></pre></td></tr></table></figure></p>
<p>返回:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">[</div><div class="line">    &#123;</div><div class="line">        &quot;id&quot;: 1,</div><div class="line">        &quot;name&quot;: &quot;学生A&quot;,</div><div class="line">        &quot;age&quot;: 16</div><div class="line">    &#125;,</div><div class="line">    &#123;</div><div class="line">        &quot;id&quot;: 2,</div><div class="line">        &quot;name&quot;: &quot;学生B&quot;,</div><div class="line">        &quot;age&quot;: 17</div><div class="line">    &#125;</div><div class="line">]</div></pre></td></tr></table></figure></p>
<p>控制台打印:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">开始查询...</div><div class="line">Studnet设置第一页两条数据!</div><div class="line">2018-04-27 19:54:56.155 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT         : ==&gt;  Preparing: SELECT count(0) FROM t_student WHERE 1 = 1 </div><div class="line">2018-04-27 19:54:56.155 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT         : ==&gt; Parameters: </div><div class="line">2018-04-27 19:54:56.156 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.S.findByListEntity_COUNT         : &lt;==      Total: 1</div><div class="line">2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity      : ==&gt;  Preparing: select id, name, age from t_student where 1=1 LIMIT ? </div><div class="line">2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity      : ==&gt; Parameters: 2(Integer)</div><div class="line">2018-04-27 19:54:56.157 DEBUG 6152 --- [nio-8084-exec-8] c.p.d.c.StudentDao.findByListEntity      : &lt;==      Total: 2</div><div class="line">总共有:3条数据,实际返回:2两条数据!</div></pre></td></tr></table></figure>
<p>查询完毕之后，我们再来看Druid 的监控界面。在浏览器输入:<a href="http://127.0.0.1:8084/druid/index.html" target="_blank" rel="external">http://127.0.0.1:8084/druid/index.html</a></p>
<p><img src="https://img-blog.csdn.net/20180427222208271?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FhendzeHBjbQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></p>
<p>可以很清晰的看到操作记录!<br>如果想知道更多的Druid相关知识，可以查看官方文档!</p>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>这篇终于写完了，在进行代码编写的时候，碰到过很多问题，然后慢慢的尝试和找资料解决了。本篇文章只是很浅的介绍了这些相关的使用，在实际的应用可能会更复杂。如果有有更好的想法和建议，欢迎留言进行讨论！</p>
<p>参考文章:<a href="https://www.bysocket.com/?p=1712" target="_blank" rel="external">https://www.bysocket.com/?p=1712</a></p>
<p>Durid官方地址:<a href="https://github.com/alibaba/druid" target="_blank" rel="external">https://github.com/alibaba/druid</a></p>
<p>PageHelper官方地址:<a href="https://github.com/pagehelper/Mybatis-PageHelper" target="_blank" rel="external">https://github.com/pagehelper/Mybatis-PageHelper</a></p>
<p>项目我放到github上面去了:<br><a href="https://github.com/xuwujing/springBoot" target="_blank" rel="external">https://github.com/xuwujing/springBoot</a></p>
<p>如果觉得不错，希望顺便给个star。<br>到此，本文结束，谢谢阅读。</p>
<p>版权声明:<br>作者：虚无境<br>博客园出处：<a href="http://www.cnblogs.com/xuwujing" target="_blank" rel="external">http://www.cnblogs.com/xuwujing</a><br>CSDN出处：<a href="http://blog.csdn.net/qazwsxpcm" target="_blank" rel="external">http://blog.csdn.net/qazwsxpcm</a>　　　　<br>个人博客出处：<a href="http://www.panchengming.com" target="_blank" rel="external">http://www.panchengming.com</a><br>原创不易，转载请标明出处，谢谢！</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>
     
    <div>
	 +
	  
<div style="text-align:center;color: #ccc;font-size:14px;">
------ 本文结束 ------</div>
<br/>
<div style="border: 1px solid black">
<div style="margin-left:10px">
<span style="font-weight:blod">版权声明</span>
<!-- <img src="/images/xuwujing.png" > -->
<br/>
<p style="font-size: 10px;line-height: 30px"><a href="http://www.panchengming.com/" style="color:#258FC6">xuwujing's Notes</a> by <a href="http://www.panchengming.com/" style="color:#258FC6">ChengMing Pan</a> is licensed under a <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/" style="color:#258FC6">Creative Commons BY-NC-ND 4.0 International License</a>.<br/>
由<a href="http://www.panchengming.com/" style="color:#258FC6">虚无境</a>创作并维护的<a href="http://www.panchengming.com/" style="color:#258FC6">xuwujing's Notes</a>博客采用<a href="https://creativecommons.org/licenses/by-nc-nd/4.0/" style="color:#258FC6">创作共用保留署名-非商业-禁止演绎4.0国际许可证</a>。<br/>
本文首发于<a href="http://www.panchengming.com/" style="color:#258FC6">xuwujing's Notes</a> 博客（ <a href="http://www.panchengming.com/" style="color:#258FC6">http://www.panchengming.com/</a> ），版权所有，侵权必究。</p>
</div>
</div>

	
	</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/springboot/" rel="tag"># springboot</a>
          
            <a href="/tags/mybatis/" rel="tag"># mybatis</a>
          
            <a href="/tags/druid/" rel="tag"># druid</a>
          
            <a href="/tags/pagehelper/" rel="tag"># pagehelper</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/04/19/pancm80/" rel="next" title="Java基础知识回顾之四 ----- 集合List、Map和Set">
                <i class="fa fa-chevron-left"></i> Java基础知识回顾之四 ----- 集合List、Map和Set
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/05/07/pancm82/" rel="prev" title="SpringBoot整合ElasticSearch实现多版本的兼容">
                SpringBoot整合ElasticSearch实现多版本的兼容 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/xuwujing.png"
               alt="虚无境" />
          <p class="site-author-name" itemprop="name">虚无境</p>
           
              <p class="site-description motion-element" itemprop="description">The way of the future!</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">136</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">30</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">59</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xuwujing" target="_blank" title="github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/qazwsxpcm?viewmode=list" target="_blank" title="csdn">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  csdn
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://home.cnblogs.com/u/xuwujing/" target="_blank" title="cnblogs">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  cnblogs
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.woainia.site/" title="woainia" target="_blank">woainia</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="chenssy" target="_blank">chenssy</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://italker.imisty.cn" title="xiaowu" target="_blank">xiaowu</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Druid介绍和使用"><span class="nav-number">2.</span> <span class="nav-text">Druid介绍和使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多数据源配置"><span class="nav-number">3.</span> <span class="nav-text">多数据源配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PageHelper-分页实现"><span class="nav-number">4.</span> <span class="nav-text">PageHelper 分页实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">5.</span> <span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">虚无境</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
 | 
本站总访问量<span id="busuanzi_value_site_pv"></span>次
 | 
本站访客数<span id="busuanzi_value_site_uv"></span>人次
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=857896&auto=0&height=66"></iframe>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
